package com.easypan.service.impl;

import com.easypan.entity.constants.Constants;
import com.easypan.service.FileProcessingStrategy;
import com.easypan.utils.ProcessUtils;
import com.easypan.utils.ScaleFilter;

import java.io.File;

/**
 * @author cyb
 * @create 2024-12-17-19:07
 * @description 实现具体策略类
 */
public class VideoProcessingStrategy implements FileProcessingStrategy {

    @Override
    public void processFile(String fileId, String targetFilePath, String month, String currentUserFolderName, String targetFolderName) {
        // 切片
        cutFile4Video(fileId, targetFilePath);

        // 视频生成缩略图
        String cover = month + "/" + currentUserFolderName + Constants.IMAGE_PNG_SUFFIX;
        String coverPath = targetFolderName + "/" + cover;

        // 通过ffmpeg生成封面
        ScaleFilter.createCover4Video(new File(targetFilePath), Constants.LENGTH_150, new File(coverPath));
    }
    // 流程：比如mp4 => .ts ，然后切割，然后删除ts文件
    private void cutFile4Video(String fileId, String videoFilePath) {
        //创建同名切片目录
        File tsFolder = new File(videoFilePath.substring(0, videoFilePath.lastIndexOf(".")));
        if (!tsFolder.exists()) {
            tsFolder.mkdirs();
        }
        // ffmpeg命令
        final String CMD_TRANSFER_2TS = "ffmpeg -y -i %s  -vcodec copy -acodec copy -vbsf h264_mp4toannexb %s";
        final String CMD_CUT_TS = "ffmpeg -i %s -c copy -map 0 -f segment -segment_list %s -segment_time 30 %s/%s_%%4d.ts";

        String tsPath = tsFolder + "/" + Constants.TS_NAME;
        // 生成.ts
        String cmd = String.format(CMD_TRANSFER_2TS, videoFilePath, tsPath);
        // Java执行ffmpeg命令工具
        ProcessUtils.executeCommand(cmd, false);
        //生成索引文件.m3u8 和切片.ts
        cmd = String.format(CMD_CUT_TS, tsPath, tsFolder.getPath() + "/" + Constants.M3U8_NAME, tsFolder.getPath(), fileId);
        ProcessUtils.executeCommand(cmd, false);
        // 删除index.ts
        new File(tsPath).delete();
    }
}